<template>
  <div class="csr" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="query" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="agen">
                  <span class="age">{{$t('public.agent')}}：</span>
                  <!-- <el-select size="mini" v-model.trim="selectedAgentList" multiple filterable :placeholder="$t('public.pickAgent')">
                    <el-option
                      v-for="item in agentOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select> -->
                  <m7Select class="el-select" :placeholder="$t('public.pickAgent')" filterable multiple :options="selectAgents" v-model="selectedAgentList"></m7Select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix label="远程服务历史报表"></affix>
    </div>
  <div :id="id">
    <div class="tab">
      <div class="export">

        <!-- <el-button class="primary_btn fr"
          v-if="$store.getters.exportFromEnd"
          @click.stop="exportXls"
        >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

        <el-button class="primary_btn fr"
          @click.stop="exportXlsx"
        >{{$t('report.exportXls')}}</el-button>

        <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
      </div>
      <div class="deploy">
        <el-collapse accordion style="display:inline-block">
          <el-collapse-item>
            <template slot="title">
              <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
            </template>
            <div>
              {{$t('report.remoteDate')}} <br>
              {{$t('report.remoteTime')}} <br>
              {{$t('report.remoteLastTime')}} <br>
              {{$t('report.remoteAgent')}} <br>
              {{$t('report.remoteCustomer')}} <br>
              {{$t('report.remoteModules')}} <br>
              {{$t('report.remoteSatisfaction')}}
            </div>
          </el-collapse-item>
        </el-collapse>
        <div class="pagina fr">
          <pagination
            small=""
            :currentPage="currentPage"
            :count="count"
            @turnPage="turnPage"
            :totalPage="Math.ceil(count/10)"></pagination></div>
      </div>
      <report-table :data="tableData" :config="headOptions.Config"></report-table>
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
        <span>{{$t('report.reportExportTipTitle')}}</span>
        <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
      </el-dialog>
    </div>
  </div>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/crsTable.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  import { deepClone, optionTimeTypeCheck } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, checkTime, searchTime } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'remote_control_report',
    data () {
      return {
        situation: [],
        isFold: false,
        id: 'remoteassist_report_server',
        title: this.$t('report.remoteControlService'),
        loading: false,
        query: {},
        dialogVisible: false,
        selectedAgentList: [],
        tableData: [],
        agentOptions: [],
        headOptions: { Config: [], data: [] },
        currentPage: 1,
        count: 0
      }
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
        }
        return  this.agentOptions
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      Pagination
    },
    methods: {
      turnPage (pageNum) {
        this.currentPage = pageNum
        this.search()
      },
      isShowFold (bool) {
        this.isFold = bool
      },
      getAgentName (id) {
        let agent = this.$store.getters.agents[id]
        let getAgent = agent ? agent.displayName + '(' + agent.exten + ')' : ''
        return getAgent
      },
      getAgentDisplayNameAndExten (id) {
        let agent = this.$store.getters.agents[id]
        return {
          displayName: agent ? agent.displayName : '',
          exten: agent ? agent.exten : ''
        }
      },
      getSearchQueryData (isExport) {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id },
          user: {
            type: this.$store.state.session.user.type,
            moduleUsers: this.$store.state.session.user.moduleUsers
          },
          page: this.currentPage,
          pageSize: 10
        }
        if (isExport) {
          data.page = 1
          data.pageSize = 1000000
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, true, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAgentList.length > 0) {
          query.selectedAgentList = this.selectedAgentList.join(',')
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryRemoteControlServiceReport', data).then((res) => {
          // 表头
          this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
          this.tableData = res.data || []
          this.tableData.forEach(item => {
            item.agentName = this.getAgentName(item.agentId)
          })
          this.loading = false
          this.count = res.count
        })
      },
      exportXlsx () {
        var data = this.getSearchQueryData(true)
        if (!data) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryRemoteControlServiceReport', data).then((res) => {
          this.loading = false
          var tableData = res.data || []
          tableData.forEach(item => {
            var {displayName, exten} = this.getAgentDisplayNameAndExten(item.agentId)
            item.agentName = displayName
            item.agentExten = exten
          })

          var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])

          var ConfigsTemp = []
          headOptions.Config && headOptions.Config.forEach(config => {
            ConfigsTemp.push(config)
            if (config.name === 'agentName') {
              ConfigsTemp.push({
                show: config.show,
                displayname: '工号',
                name: 'agentExten'
              })
            }
          })
          headOptions.Config = ConfigsTemp

          var headers = headOptionsToXlsxHeaders(headOptions.Config)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.remoteControlService') + timeStamp)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportRemoteAssistServer',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, true, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAgentList.length > 0) {
          query.selectedAgentList = this.selectedAgentList.join(',')
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImCsrReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.remoteControlService') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agentOptions = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .csr

    .export
      .pdf
        margin-right 10px
    .tab
      .deploy
        .tip
          margin-left 0px
    .agen
      margin-top 14px
      .age
        display inline-block
        height 28px
        line-height 28px
        margin 0 16px 0 0
      .el-select
        width 400px
</style>
